﻿using Microsoft.AspNetCore.Mvc;
 
using XKPlatform.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
using XKPlatform.DataModels.ReturnModel;
using XKPlatform.DataModels;

namespace XKPlatform.Common
{
    public class InterfaceHelper
    {
        public static BaseModel SaveApi(Dictionary<MethodInfo, bool> pairs, Dictionary<string, string> nodeList,string connect="")
        {
            BaseModel BM = new BaseModel();
            try
            {
                var proid = SqlHelper.ExecuteSqlGet("select No from SysProject where ProjectName='MidEdn'", "", connect);
                if (proid == null)
                {
                    proid = "";
                }
                List<string> apisqllist = new List<string>();
                List<string> proapisqllist = new List<string>();
                var apids= SqlHelper.Query("select * from sysApi", connect);
                DataTable table = null;
                if (apids.Tables.Count > 0)
                {
                    table = apids.Tables[0];
                }
                List<sysApiModel> apilist = new List<sysApiModel>();
                foreach (KeyValuePair<MethodInfo, bool> kv in pairs)
                {
                    string UrlAddr = string.Format(@"/{0}/{1}", kv.Key.ReflectedType.Name.Replace("Controller", ""), kv.Key.Name);
                    string apiname = null;
                    string FullName = kv.Key.DeclaringType.FullName + "." + kv.Key.Name;
                    List<string> param = new List<string>();
                    var parameters = kv.Key.GetParameters();
                    foreach (ParameterInfo info in parameters)
                    {
                        param.Add(info.ParameterType.ToString());
                    }
                    if (param.Count > 0)
                    {
                        FullName += "(" + string.Join(',', param) + ")";
                    }
                    if (nodeList.ContainsKey(FullName))
                    {
                        apiname = nodeList.GetValueOrDefault(FullName);
                    }
                    if (string.IsNullOrWhiteSpace(apiname))
                    {
                        apiname = kv.Key.Name;
                    }
                    apiname = apiname.Replace("\r\n", "").Trim();
                    apiname = kv.Key.Module.ToString().Replace("dll", "") + apiname;
                    var route = kv.Key.GetCustomAttribute<RouteAttribute>();
                    if (route != null)
                    {
                        UrlAddr = string.Format(@"/{0}/{1}", kv.Key.ReflectedType.Name.Replace("Controller", ""), route.Template);
                    }
                    if(table!=null)
                    {
                        if (table.Select($"UrlAddr='{UrlAddr}'").Length > 0)
                        {
                            continue;
                        }
                    }
                    string id = Guid.NewGuid().ToString().ToUpper();
                    string sql = $"INSERT INTO sysApi (ID, ApiName, UrlAddr, ModifiedBy, RecordStatus, ModifiedOn, IsNeedPermisson) values ('{id}', '{apiname}', '{UrlAddr}','', '0', '{DateTime.Now}', {Convert.ToInt32(kv.Value)})";
                    string prosql = $"INSERT INTO SysProjectApi (ApiId, ProId) values ('{id}', '{proid}')";
                    proapisqllist.Add(prosql);
                    apisqllist.Add(sql);
                }
                if (apisqllist.Count == 0)
                {
                    BM.code = 0;
                    BM.msg = $"没有需要新增的接口。";
                }
                else
                {
                    int result= SqlHelper.ExecuteSqlTran(apisqllist, connect);
                    int result1 = SqlHelper.ExecuteSqlTran(proapisqllist, connect);
                    if (result == apisqllist.Count)
                    {
                        BM.code = 0;
                        BM.msg = $"保存接口成功，共保存{apisqllist.Count}个接口。";
                    }
                    else
                    {
                        BM.code = 1;
                        BM.msg = $"保存接口部分成功，共保存{apisqllist.Count}个接口，其中{apisqllist.Count - result}个失败。";
                    }
                }
            }
            catch(Exception ex)
            {
                BM.code = 1;
                BM.msg="保存接口失败，错误信息："+ex.Message;
            }
            return BM;
        }
    }
}
